﻿using System.Net;

using BodaNetCommunications.Cores;
using BodaNetCommunications.Utilities.Results;

namespace BodaNetCommunications.TcpComs
{
    public class TcpClient : ICommDevice
    {
        public ConnectionOptions Options { get; private set; }

        public bool IsConnected => _commUnit != null && _commUnit.IsConnected;

        private ICommUnit _commUnit;

        public TcpClient()
        {

        }
        public BodaResult Connect(ConnectionOptions connectionOptions)
        {
            BodaResult bodaResult = new BodaResult();
            Options = connectionOptions;

            if (string.IsNullOrEmpty(Options.Ip) || false == IPAddress.TryParse(Options.Ip, out _))
            {
                bodaResult.IsSuccess = false;
                bodaResult.Message = $"Ip[{Options.Ip}]为空或者格式不正确";
                return bodaResult;
            }

            if (Options.Port < 0 || Options.Port > 65535)
            {
                bodaResult.IsSuccess = false;
                bodaResult.Message = $"Port[{Options.Port}]不正确";
                return bodaResult;
            }

            if (IsConnected)
            {
                bodaResult.IsSuccess = true;
                bodaResult.Message = $"Tcp【{Options.Ip}:{Options.Port}】的连接已经在线，不需要重复连接";
                return bodaResult;
            }

            _commUnit = new CommUnitTcp(Options.Ip, Options.Port);

            return _commUnit.Open(Options.ConnectTimeout);
        }

        public void Disconnect()
        {
            _commUnit?.Close();
        }

        public BodaResult SendMsgc(byte[] bytes, int timeout = 1500)
        {
           return _commUnit.SendMsgc(bytes, timeout);
        }

        public BodaResult<byte> ReceiveMsg(int timeout = 2000, int bytesLen = 1024)
        {
            return _commUnit.ReceiveMsg(timeout, bytesLen);
        }
    }
}
